package com.lixingye.meowstar.controller;

import com.lixingye.meowstar.common.AppResult;
import com.lixingye.meowstar.common.ResultCode;
import com.lixingye.meowstar.config.AppConfig;
import com.lixingye.meowstar.model.User;
import com.lixingye.meowstar.service.IUserService;
import com.lixingye.meowstar.utils.MD5Util;
import com.lixingye.meowstar.utils.StringUtil;
import com.lixingye.meowstar.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 猫大仙
 * @since 2025-01-14
 */
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     * 用户注册
     * @param username
     * @param password
     * @param nickname
     * @param passwordRepeat
     * @return
     */
    @Operation(summary = "用户注册")
    @PostMapping( "/register")
    public AppResult register(@Parameter(name = "username",description = "用户名") @RequestParam("username") @NonNull String username,
                              @Parameter(name = "password",description = "密码") @RequestParam("password") @NonNull String password,
                              @Parameter(name = "nickname",description = "昵称") @RequestParam("nickname") @NonNull String nickname,
                              @Parameter(name = "passwordRepeat",description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
//        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)
//                || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(passwordRepeat)){
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //校验密码与确认密码是否相同
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username); user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        user.setSalt(salt);
        String cipherText = MD5Util.md5Salt(password, salt);
        user.setPassword(cipherText);
        userService.createNormalUser(user);
        return AppResult.success(user);
    }
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(@Parameter(name = "username",description = "用户名") @RequestParam("username") @NonNull String username,
                           @Parameter(name = "password",description = "密码") @RequestParam("password") @NonNull String password,
                           HttpServletRequest request){
        User user = userService.login(username, password);
        //登录成功把User设置到session作用域中 没有session要创建
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }
    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
        @Parameter(name = "id",description = "用户id") @RequestParam(value = "id",required = false)Long id){
        User user = null;
        //如果id为空，则从session中获取用户信息
        if(id == null){
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //如果id不为空，则从数据库中获取用户信息
            user = userService.getByUserId(id);
            if(user == null){
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
        }
        return AppResult.success(user);
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session!=null){
            log.info("用户退出登录");
            //表示用户已经登录，则清除session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param request
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param phoneNum
     * @param remark
     * @return
     */
    @Operation(summary = "修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(name = "username",description = "用户名") @RequestParam(value = "username",required = false) String username,
                                @Parameter(name = "nickname",description = "用户昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @Parameter(name = "gender",description = "用户性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @Parameter(name = "email",description = "用户邮箱") @RequestParam(value = "email",required = false) String email,
                                @Parameter(name = "phoneNum",description = "用户电话") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @Parameter(name = "remark",description = "用户简介") @RequestParam(value = "remark",required = false) String remark){
        //非空校验
        if(StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && gender==null
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
        ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //进行修改
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        User newuser = userService.getByUserId(user.getId());
        //把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,newuser);
        return AppResult.success(newuser);
    }


    @Operation(summary = "修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Parameter(name = "oldPassword",description = "原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @Parameter(name = "newPassword",description = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @Parameter(name = "passwordRepeat",description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验新密码与确认密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前用户登录信息
        HttpSession session = request.getSession(false);
        User user  = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁session
        if(session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }
}
